import { nextTick, ref } from "vue";
import html2canvas from "html2canvas";
import { jsPDF } from "jspdf";
import { defineStore } from "pinia";
import dayjs from "dayjs";


// 延迟
export function sleep(duration: number) {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(true);
        }, duration);
    });
}

export const usePDF = () => {
    const doc = new jsPDF({
        orientation: "p",
        unit: "px",
        format: "a4"
    });

    const store = defineStore("pdf", () => {
        const expand = ref(false);
        const loading = ref(false);

        async function toPDF({
            name,
            target,
            width,
            scope,
            flat
        }: {
            name?: string;
            target: any;
            width?: string;
            scope: any;
            flat: 'download' | 'print'
        }) {
            if (!name) {
                name = scope.name || dayjs().format("YYYY-MM-DD HH:mm:ss") + "_" + "销售合同";
            }

            expand.value = true;
            loading.value = true;

            await nextTick();
            await sleep(1000);

            const a = document.querySelector(target!);

            const canvas = await html2canvas(a, {
                scale: 1.2,
                useCORS: true
            })

            const url = canvas.toDataURL();

            try {
				const img = new Image();

				img.src = url;

                // 同步等待图片加载完成
                await new Promise((resolve, reject) => {
                    img.onload = resolve;
                    img.onerror = reject;
                });

                // img.onload = () => {
                // 图片的大小
                const imgWidth = doc.internal.pageSize.width;
                const imgHeight = (img.height * imgWidth) / img.width;

                // pdf的大小
                const pageHeight = doc.internal.pageSize.height;
                const pageWidth = doc.internal.pageSize.width;

                console.log(imgWidth, imgHeight);
                console.log(pageWidth, pageHeight);

                let startY = 0;

                while (startY < imgHeight) {
                    const remainingHeight = imgHeight - startY;
                    const height = Math.min(remainingHeight, pageHeight);

                    doc.addImage(
                        url,
                        "JPEG",
                        0,
                        -startY,
                        pageWidth,
                        imgHeight,
                        undefined,
                        "FAST"
                    );

                    startY += height;

                    if (startY < imgHeight) {
                        doc.addPage();
                    }
                }

                expand.value = false;
                loading.value = false;

                // doc.save(`${name || "demo"}.pdf`);
                // b.remove();

                // 保存文件流
                const pdfBlob: any = doc.output("datauristring");

                // 使用 Blob 保存文件流
                // const pdfBlob: any = doc.output("blob");
                // // pdfBlob.name = `${name || "demo"}.pdf`;
                // pdfBlob.name = `.pdf`;
                // console.info("pdfBlob", pdfBlob)
                
                // doc.save(`${name || "demo"}.pdf`);

                return pdfBlob

                if (flat === "print") {
                    doc.autoPrint();
                    window.open(doc.output('bloburl'), '_blank');
                } else {
                    doc.save(`${name || "demo"}.pdf`);
                }
                // b.remove();
            } catch (err) {
                console.error(err);
                loading.value = false;
            }
        }

        return {
            expand,
            loading,
            toPDF
        };
    });

    return store();
};
